/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Model;

import java.util.Date;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;

/**
 *
 * @author sergey
 */
public class CRecord extends Object{

    public CRecord(CCurrency cur, Date date, CCategory cat, int amount)
    {
        this.m_currency = cur;
        this.m_category = cat;
        this.m_nAmount = amount;
        this.m_date = date;
    }
    public CCurrency m_currency;
    public Date m_date;
    public CCategory m_category;
    public String m_Notes;
    public int m_nAmount;
    
    private int GetCategory(CCategory[] cat)
    {
        for (int i =0; i< cat.length; ++i)
            if (cat[i] == m_category)
                return i;
        return 0;
    }
    public int GetCurrency(CCurrency[] cur)
    {
        for (int i =0; i< cur.length; ++i)
            if (cur[i] == m_currency)
                return i;
        return 0;
    }

    public byte[] getBytes(CCategory[] categories, CCurrency[] curencies)
    {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        DataOutputStream outputDataStream = new DataOutputStream(outputStream);
        try
        {
            outputDataStream.writeInt(GetCategory(categories));
            outputDataStream.writeInt(GetCurrency(curencies));
            outputDataStream.writeInt(m_nAmount);
            outputDataStream.writeLong(m_date.getTime());
            if (m_Notes.length() > 0)
                outputDataStream.write(Encoder.getBytes(m_Notes));
        }
        catch( Exception e)
        {
            e.printStackTrace();
        }

        return outputStream.toByteArray();
    }

    public void fromBytes(byte[] arr, CCategory[] categories, CCurrency[] curencies)
    {

        try{
            ByteArrayInputStream inputStream = new ByteArrayInputStream(arr);
            DataInputStream inputDataStream = new DataInputStream(inputStream);

            
            m_category = categories[inputDataStream.readInt()];
            m_currency = curencies[inputDataStream.readInt()];
            m_nAmount = inputDataStream.readInt();
            m_date = new Date();
            m_date.setTime(inputDataStream.readLong());
            if (arr.length - 20 > 0)
            {
                byte[] note = new byte[arr.length - 20];
                inputDataStream.read(note);
                m_Notes = Encoder.fromBytes(note);
            }
            else
                m_Notes = new String();
            
        }
        catch( Exception e)
        {
            e.printStackTrace();
        }
    }
}
